<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" show-icon :closable="false" center></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="+activeIndex" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 使用表单把左侧标签提示框包裹起来 -->
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsFormRules"
        ref="addGoodsFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- 左侧标签提示栏  before-leave满足条件后才能换到下一个 tab-click：tab被选中时触发-->
        <!-- 让v-model绑定同一个数据，进行联动效果 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 级联选择框 -->
            <!-- options:要渲染的数据 :props:配置级联选择框 @change时刻监听级联选择器 -->
            <el-cascader
              v-model="addGoodsForm.goods_cat"
              :options="CateList"
              :props="setCascader"
              @change="cateListChange"
              clearable
              change-on-select
            ></el-cascader>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in paramsList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item1"
                  v-for="(item1,index1) in item.attr_vals"
                  :key="index1"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in staticProperty"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片 action图片上传的地址 :on-preview点击预览图片 :on-remove点击删除图片 list-type设置图片的展示样式 :headers设置提交的请求头 on-success文件上传成功时的回调函数-->
            <el-upload
              :action="actionURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="onSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 要设置样式必须在全局样式才能设置-->
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addCate" @click="submitCate">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 展示放大图片的对话框 -->
    <el-dialog title="图片预览" :visible.sync="imgDialogVisible" width="60%">
      <img :src="serverImgURL" alt="" style="width:100%">
    </el-dialog>
  </div>
</template>

<script>
// 导入深拷贝js
import _ from 'lodash'
export default {
  data () {
    return {
      // 把提示区域和左侧标签提示框联系起来的数据
      activeIndex: '0',
      // 表单数据
      addGoodsForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        // 传过去的时候，不能是一个数组(商品所属分类)
        goods_cat: [],
        // 用于保存服务器返回的临时图片
        pics: [],
        // 商品描述
        goods_introduce: '',
        attrs: []
      },
      // 表单验证
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 获取商品分类数据列表
      CateList: [],
      // 配置级联选择框
      setCascader: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数列表
      paramsList: [],
      // 静态属性参数
      staticProperty: [],
      // 图片提交地址
      actionURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 设置图片提交请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 服务器返回的图片真实路径
      serverImgURL: '',
      // 图片放大对话框的显示与隐藏
      imgDialogVisible: false
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品列表数据
    async getCateList() {
      const { data: res } = await this.axios.get('categories')
      if (res.meta.status !== 200) return this.msg.error('获取商品列表数据失败')
      this.CateList = res.data
    },
    // 当级联选择框选择项变化时触发
    cateListChange() {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    // tabs满足条件后，才能换到下一个
    // 第一个参数是到哪里去(新值)，第二个参数是从那里来(旧值)
    beforeLeave(newActive, oldActive) {
      if (oldActive === '0') {
        if (this.addGoodsForm.goods_cat.length !== 3) {
          return false
        } else if (oldActive === '1') {
          // 获取动态参数
        }
      }
    },
    // tab被选中时触发
    async tabClick() {
      if (this.activeIndex === '1') {
        // 获取动态参数列表
        const { data: res } = await this.axios.get(`categories/${this.addGoodsForm.goods_cat[2]}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.msg.error('获取参数列表失败')
        // 把attr_vals变成一个数组，方便渲染
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })
        this.paramsList = res.data
      } else if (this.activeIndex === '2') {
        // 获取静态属性列表
        const { data: res } = await this.axios.get(`categories/${this.addGoodsForm.goods_cat[2]}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.msg.error('获取动态属性列表失败')
        this.staticProperty = res.data
      }
    },
    // 点击预览图片
    handlePreview(file) {
      this.serverImgURL = file.response.data.url
      this.imgDialogVisible = true
    },
    // 点击删除图片
    handleRemove(file) {
      // 拿到图片临时路径的索引，从而在数组中删除
      const index = this.addGoodsForm.pics.findIndex(item => {
        return item.pic === file.response.data.tmp_path
      })
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 图片上传成功时的回调函数
    onSuccess(response) {
      // 把服务器返回的临时图片路径添加到里面去
      this.addGoodsForm.pics.push({ pic: '/' + response.data.tmp_path })
    },
    // 点击添加商品
    submitCate() {
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) {
          return this.msg.error('请填写必要的表单项')
        }
        const addForm = _.cloneDeep(this.addGoodsForm)
        addForm.goods_cat = addForm.goods_cat.join(',')
        // 处理动态参数
        this.paramsList.forEach(item => {
          const listInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          addForm.attrs.push(listInfo)
        })
        // 处理静态属性
        this.staticProperty.forEach(item => {
          const listInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          addForm.attrs.push(listInfo)
        })
        // 商品名称是唯一的
        const { data: res } = await this.axios.post('goods', addForm)
        if (res.meta.status !== 201) return this.msg.error('添加商品失败')
        this.msg('添加商品成功')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped lang="less">
  .el-steps {
    margin: 25px 0;
  }
  .el-checkbox {
    margin: 0 15px 0 0!important;
  }
  .addCate {
    margin-top: 15px;
  }
</style>
